package com.empress.uranus.zma.common.utils;

import com.empress.uranus.zma.common.constants.MCConstant;

public class SecureUtil {

	/**
	 * 校验报文CRC
	 * @param packetBytes 报文字节数组
	 * @param length 报文字节数组长度
	 * @param matchValue 待匹配值
	 * @return 报文crc校验是否正确
	 */
	public static boolean checkPacketCrc16(byte[] packetBytes, int length, int matchValue){
		
		if(packetBytes == null || length < 8){
			
			return false;
		}
		if(MCConstant.MC_ENV_TEST){
			if(packetBytes[5] == 0x01){
				packetBytes[5] = 0x71;
			}
			else if(packetBytes[5] == 0x03){
				packetBytes[5] = 0x72;
			}
			else if(packetBytes[5] == 0x05){
				packetBytes[5] = 0x73;
			}
			else if(packetBytes[5] == 0x07){
				packetBytes[5] = 0x74;
			}
			else{
				return false;
			}
		}
		
		int crcValue = MessageFormatUtil.CalcCrc16_2(MessageFormatUtil.changeBytesToChars(packetBytes, length), length-2);
		byte[] crcValueBytes = MessageFormatUtil.longToBytes(crcValue, 2);
    	Integer crcValueChanged = MessageFormatUtil.bytesToNumber(crcValueBytes, 2);
		return crcValueChanged == matchValue;
	}
}
